<template>
    <van-form class="flex flex-col justify-around">
        <van-field
            class="field"
            type="username"
            label="邮箱"
            placeholder="请输入邮箱"
            v-model="input.username"
            :rules="[{ pattern: pattern.username, message: '邮箱格式错误' }]"
        >
            <div slot="left-icon" class="Icon">account_circle</div>
        </van-field>
        <van-field
            type="password"
            label="密码"
            v-model="input.password"
            placeholder="请输入密码"
            :rules="[
                {
                    pattern: pattern.password,
                    message:
                        '必须有数字，密码长度最少8位，大写字母，小写字母，数字，特殊符号中必须具有三种',
                },
            ]"
        >
            <span slot="left-icon" class="Icon">password</span></van-field
        >
        <van-field
            type="password"
            label="重复密码"
            v-model="secondPwd"
            placeholder="请输入密码"
            :rules="[{ validator: secondPwdValid, message: '重复密码错误' }]"
        >
            <span slot="left-icon" class="Icon">password</span></van-field
        >

        <van-button
            type="primary"
            class="rounded-xl"
            size="large"
            @click="signUp"
            :loading="loading"
            >注册</van-button
        >
    </van-form>
</template>

<script>
import { mapActions } from "vuex";
import timeLimit from "@/utils/timeLimit.js";
export default {
    data() {
        return {
            loading: false,
            input: {
                username: "",
                password: "",
            },
            secondPwd: "",
            pattern: {
                username:
                    /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
                password:
                    /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,}$/,
            },
        };
    },
    methods: {
        ...mapActions(["SignUp", "Reset"]),
        async signUp() {
            const protect = timeLimit({
                key: "LastSignUpTime",
                message(timeout) {
                    return `5 分钟内曾经注册过，请等待 ${Math.ceil(
                        timeout / 1000
                    )} 秒`;
                },
            });
            if (protect) return;

            this.loading = true;
            const isEmail = this.input.username.match(/@/);
            const data = { type: isEmail ? "email" : "user", ...this.input };
            await this.SignUp(data);
            this.loading = false;
        },
        secondPwdValid() {
            return this.secondPwd === this.input.username;
        },
    },
};
</script>

<style lang="less" scoped>
.field {
    @apply items-center justify-evenly bg-transparent;
}
.Icon {
    @apply text-blue-500 cursor-default text-2xl mx-2;
}
</style>
